package org.lightrpc.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.lightrpc.RemoteCallFailedException;
import org.lightrpc.RemoteCallUrl;
import org.lightrpc.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class creates http remote calls using the RemoteCallUrl object.
 * 
 * @author miku
 * 
 */
public class HttpRemoteClient implements RemoteClient {
	private static final Logger logger = LoggerFactory
			.getLogger(HttpRemoteClient.class);

	private static final String HTTP_PROTOCOL = "http";

	@Override
	public Response callService(RemoteCallUrl urlModel)
			throws RemoteCallFailedException {

		String path;

		if (urlModel.getRootPath() != null)
			path = urlModel.getRootPath() + urlModel.getServicePath();
		else
			path = urlModel.getServicePath();

		try {
			URL url = new URL(HTTP_PROTOCOL, urlModel.getHost(), urlModel
					.getPort(), path);
			URLConnection urlConnection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(url
					.openStream()));

			String inputLine;
			String data = "";
			while ((inputLine = in.readLine()) != null)
				data += inputLine;			

			Response remoteData = new Response(new String(data));
			remoteData.setStatus(urlConnection
					.getHeaderField(Response.RPC_STATUS_NAME));
			in.close();
			
			return remoteData;
		} catch (MalformedURLException e) {
			// TODO add more specific error message
			logger
					.error("Illegal URL. Cannot connect to this remote object",
							e);
			throw new RemoteCallFailedException(
					"Illegal URL:" + e.getMessage(), e);
		} catch (IOException e) {
			// TODO add more specific error message (it might not be required to
			// log this here because the exception is rethrown)
			logger
					.error(
							"Cannot read from source. Please check remote object address",
							e);
			throw new RemoteCallFailedException("Fatal transport error:"
					+ e.getMessage(), e);
		}
	}

}
